package net.hands.ado;

import java.io.IOException;
import java.util.Properties;

import javax.sql.DataSource;

import net.hands.ado.db.DBTablesFactory;
import net.hands.ado.db.jdbc.DefaultJdbcProvider;
import net.hands.common.ClassUtils;
import net.hands.common.ClassUtils.IScanResourcesCallback;
import net.hands.common.I18n;
import net.hands.common.ISettings;

import com.alibaba.druid.pool.DruidDataSource;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;

public class ADOModule extends AbstractModule {

	protected final Properties properties = new Properties();

	@Override
	protected void configure() {
		try {
			properties.load(this.getClass().getResourceAsStream(
					ISettings.PRONAME));
		} catch (IOException e) {
			e.printStackTrace();
		}
		bind(DataSource.class).toInstance(getDataSource());
		// 初始化资源
		try {
			doScanResources(getScanPackageNames());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void doScanResources(final String[] packageNames)
			throws Exception {
		final IScanResourcesCallback proCallback = I18n.getBasenamesCallback();
		final IScanResourcesCallback tableCallback = DBTablesFactory
				.getDBTablesCallback();
		for (final String packageName : packageNames) {
			ClassUtils.scanResources(packageName, proCallback, tableCallback);
		}
	}

	public String[] getScanPackageNames() {
		return new String[] { "net.hands" };
	}

	protected DataSource getDataSource() {
		DruidDataSource dataSource;
		try {
			dataSource = (DruidDataSource) ClassUtils.forName(
					properties.getProperty(ISettings.DBPOOL_PROVIDER))
					.newInstance();
			dataSource.setDriverClassName(properties
					.getProperty(ISettings.DBPOOL_DRIVERCLASSNAME));
			dataSource.setUrl(properties.getProperty(ISettings.DBPOOL_URL));
			dataSource.setUsername(properties
					.getProperty(ISettings.DBPOOL_USERNAME));
			dataSource.setPassword(properties
					.getProperty(ISettings.DBPOOL_PASSWORD));
			return dataSource;
		} catch (InstantiationException | IllegalAccessException
				| ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;

	}

	public static void main(String[] args) {
		Injector inj = Guice.createInjector(new ADOModule());
		DefaultJdbcProvider djp = inj.getInstance(DefaultJdbcProvider.class);
		DBTablesFactory.updateTables(djp);

	}

}
